package com.nulldev.util.web.nCaptcha.backend;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.URIUtil2;
import com.nulldev.util.uri.server.HttpPage;
import com.nulldev.util.uri.server.RequestType;
import com.nulldev.util.web.nCaptcha.nCaptcha;
import com.nulldev.util.web.nCaptcha.backend.user.User;
import com.nulldev.util.web.nCaptcha.backend.user.UserManager;

public class CheckCaptcha extends HttpPage {

	public CheckCaptcha() {
		super("/check_captcha");
	}
	

	@Override
	public String handleRequest(String args, String ip, RequestType type) {
		final User user = UserManager.registerOrLoadUser(ip);
		final Map<String, List<String>> requests = URIUtil2.splitQuery(URIUtil.safeCreate(args));
		//final String input = args.replaceAll(Pattern.quote("/check_captcha?input="), "");
		final List<String> input = requests.get("input");
		if (input == null || input.size() == 0) {
			user.captchaFailed();
			return "failed::0" + "\n" + user.getUID();
		}
		if (user.getExpectedResults() == null || user.getExpectedResults().length == 0 || input.get(0) == null) {
			user.captchaFailed();
			return "failed::0" + "\n" + user.getUID();
		}
		final boolean passed = user.validExpectedResult(input.get(0));
		if (passed) {
			user.captchaPassed();
			return "passed::1" + "\n" + user.getUID();
		}else {
			user.captchaFailed();
			return "failed::0" + "\n" + user.getUID();
		}
	}

	/**
	 * Unused
	 */
	@Override
	public byte[] handleRequest_Alt(String args, String ip, RequestType type) {
		return null;
	}
}
